package testndk.testservice;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import testndk.testservice.service.MessengerService;
public class MessageActivity extends Activity {

	private boolean mIsBind;
	private Button startBtn = null;
	private Button stopBtn = null;
	private TextView mTextView = null;
	/** 从服务端获取的信使*/
	private Messenger rMessenger = null;
	/** 本地信使*/
	private Messenger mMessenger = null;

	private Intent intent = null;
	private ProgressBar mProgressBar = null;
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case MessengerService.TEST:
				int curLoad = msg.arg1;
				mTextView.setText(curLoad+"%");
				mProgressBar.setProgress(curLoad);
				break;

			default:
				break;
			}
		}
	};
	private ServiceConnection serConn = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			rMessenger = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			rMessenger = new Messenger(service);//get the object of remote service
			mMessenger = new Messenger(mHandler);//initial the object of local service
			sendMessage();
		}
	};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        intent = new Intent(this,MessengerService.class);
        mProgressBar = (ProgressBar)findViewById(R.id.myProgressBar);
        mProgressBar.setMax(100);
        mTextView = (TextView)findViewById(R.id.loading_Tv);
        startBtn = (Button)findViewById(R.id.start_Btn);
        stopBtn = (Button)findViewById(R.id.stop_Btn);
        startBtn.setOnClickListener(new ButtonClickListener());
        stopBtn.setOnClickListener(new ButtonClickListener());
        
    }


	class ButtonClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (startBtn == v) {
				mIsBind = bindService(intent, serConn, Context.BIND_AUTO_CREATE);//if bind success return true
			} else if (stopBtn == v) {
				if(mIsBind){
					unbindService(serConn);
					mIsBind = false;
				}
			}
		}

	}
	/** 向服务端发信息*/
	private void sendMessage() {
		Message msg = Message.obtain(null, MessengerService.TEST);//MessengerService.TEST=0
		msg.replyTo = mMessenger;
		try {
			rMessenger.send(msg);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
}